package com.campuscarbooking.api.scheduler;

import com.campuscarbooking.api.model.Reservation;
import com.campuscarbooking.api.model.BusSchedule;
import com.campuscarbooking.api.repository.ReservationRepository;
import com.campuscarbooking.api.service.NotificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * Scheduler for sending reservation reminders via RabbitMQ
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class ReminderScheduler {

    private final ReservationRepository reservationRepository;
    private final NotificationService notificationService;

    /**
     * Send reminders for tomorrow's reservations at 8 PM daily
     */
    @Scheduled(cron = "0 0 20 * * ?") // Every day at 8 PM
    public void sendReservationReminders() {
        LocalTime startOfDay = LocalTime.of(0, 0);
        LocalTime endOfDay = LocalTime.of(23, 59, 59);
        log.info("Sending reminders for reservations tomorrow");

        // Find all confirmed reservations for tomorrow
        List<Reservation> tomorrowReservations = reservationRepository.findByDepartureTimeBetween(startOfDay, endOfDay);

        int count = 0;
        for (Reservation reservation : tomorrowReservations) {
            if (reservation.getStatus() == Reservation.Status.confirmed) {
                notificationService.sendReservationReminder(reservation);
                count++;
            }
        }

        log.info("Sent {} reservation reminders for tomorrow", count);
    }

    /**
     * Check for upcoming departures and send reminders 1 hour before
     */
    @Scheduled(cron = "0 0 * * * ?") // Every hour
    public void sendUpcomingDepartureReminders() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime oneHourLater = now.plusHours(1);

        LocalTime startTime = oneHourLater.toLocalTime().minusMinutes(5); // 55 minutes from now
        LocalTime endTime = oneHourLater.toLocalTime().plusMinutes(5); // 65 minutes from now

        log.info("Checking for reservations with departures between {} and {}", startTime, endTime);

        // Find reservations with departures in the next hour
        List<Reservation> upcomingReservations = reservationRepository.findByDepartureTimeBetween(startTime, endTime);

        int count = 0;
        for (Reservation reservation : upcomingReservations) {
            if (reservation.getStatus() == Reservation.Status.confirmed && !reservation.getSignedIn()) {
                notificationService.sendReservationReminder(reservation);
                count++;
            }
        }

        log.info("Sent {} departure reminders for upcoming trips", count);
    }
} 